import { history } from 'umi';
import { message } from 'antd';
import api from '../../../services';
const { queryAllTag, updateTag, addTag, delTag } = api;

export default {
  namespace: 'labelManage',

  state: {
    labelList: [],
  },

  subscriptions: {
    setupHistory({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname, state }) => {
        if (pathname === '/manageCenter/labelManage') {
          dispatch({ type: "queryTag" });
          dispatch({ type: "queryClassify" });
          return;
        }
      })
    },
  },
  effects: {
    *queryTag({ }, { put, call, select }) {
      const result = yield call(queryAllTag);
      if (result.code === 0) {
        yield put({ type: "updateState", payload: { labelList: result.data } });
      }
      else {
        message.error(result.message, 1);
      }
    },
    *queryClassify({ }, { put, call, select }) {
      const classifyList = yield select(state => state.classifyManage.classifyList);
      if (classifyList.length === 0) {
        yield put({ type: "classifyManage/queryCategory" });
      }
    },
    *addTag({ payload }, { put, call, select }) {
      const result = yield call(addTag, payload);
      if (result.code === 0) {
        yield put({ type: "queryTag" });
        message.success("添加成功");
      }
      else {
        message.error(result.message, 2);
      }
    },
    *updateTag({ payload }, { put, call, select }) {
      const result = yield call(updateTag, payload);
      if (result.code === 0) {
        yield put({ type: "queryTag" });
        message.success("修改成功");
      }
      else {
        message.error(result.message, 3);
      }
    },
    *delTag({ payload }, { put, call, select }) {
      const result = yield call(delTag, payload);
      if (result.code === 0) {
        yield put({ type: "queryTag" });
        message.success("删除成功");
      }
      else {
        message.error(result.message, 4);
      }
    },
  },
  reducers: {
    updateState(state, action) {
      return { ...state, ...action.payload };
    }
  }
};